﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace mbine.msgc.model
{
    /// <summary>
    /// 클라이언트 -> 서버
    /// </summary>
    public static class CChatMessage
    {
        /// <summary>
        /// Chat Message
        /// </summary>
        /// <param name="_kind">chat / write / writecancel / addmember / outmember</param>
        /// <param name="_sender">보내는 사람 email</param>
        /// <param name="_rcpt">수신자들(List)</param>
        /// <param name="_chat">메시지</param>
        /// <param name="_roomkey">Room Key</param>
        /// <param name="_mykey"></param>
        /// <returns></returns>
        public static string Chat(string _kind, string _sender, List<string> _rcpt, string _chat, string _roomkey, string _mykey)
        {
            string SubHeader = JsonConvert.SerializeObject(_rcpt);
            string Body = JsonConvert.SerializeObject(
                new StructChat
                { 
                    mode = "chat",
                    kind = _kind,
                    mykey =_mykey, 
                    sender = _sender, 
                    roomkey = _roomkey, 
                    data = _chat
                }
            );
            return GetData("relay", SubHeader, Body);
        }

        /// <summary>
        /// 사용자 로그인 등록 
        /// </summary>
        /// <param name="_id">사용자 Email</param>
        /// <param name="_pkey">Private Key</param>
        /// <param name="_akey">Authenticate Key</param>
        /// <returns></returns>
        public static string Login(string _id, string _pkey, string _akey)
        {

            string Body = JsonConvert.SerializeObject(
                new StructLogin
                {
                    akey = _akey,
                    email = _id,
                    pkey = _pkey,
                    roster = (from p in CRoster.Instance.Users select p.Email).ToList()
                }
            );
            return GetData("login", "0", Body);
        }

        #region Private Methods
        private static string GetData(string _header, string _subheader, string _body)
        {
            string bodySize = Encoding.UTF8.GetBytes(_body).Length.ToString();
            string subHeaderSize = Encoding.UTF8.GetBytes(_subheader).Length.ToString();
            while (12 > _header.Length)
            {
                _header = " " + _header;
            }
            while (8 > subHeaderSize.Length)
            {
                subHeaderSize = " " + subHeaderSize;
            }
            while (8 > bodySize.Length)
            {
                bodySize = " " + bodySize;
            }

            return _header + subHeaderSize + bodySize + _subheader + _body;
        }
        #endregion
    }
}